import Vue from 'vue'
import VueRouter from 'vue-router'
let Home = () => import('../components/Home.vue')
let Login = () => import('../components/Login.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/home',
    name: 'Home',
    component: Home
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    redirect: '/home'
  }
]

const router = new VueRouter({
  routes
})

//避免重复点击当前页面的路径提示异常，不影响程序的正常执行
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(to) {
  return VueRouterPush.call(this, to).catch(err => err)
}
//路由的前置守卫
router.beforeEach(function(to, from, next) {
  console.log(to)
  console.log(from)
  let toPath = to.path
  //设置访问页的标题
  document.title = getTitle(toPath)
  //对注册、登录页不拦截
  if (
    toPath === '/' ||
    toPath === '/login' ||
    toPath === '/register' ||
    toPath === '/home'
  ) {
    //放行
    return next()
  }
  //对其它页面进行拦截
  let user = sessionStorage.getItem('USER_LOGIN')
  if (user) {
    //Vue.prototype.$message.success('登录成功')
    return next()
  }
  Vue.prototype.$message.error('你没有登录')
  //回到首页或登录页
  next('/')
})

//路由的后置守卫
router.afterEach(function(to, from) {
  console.log(to)
  console.log(from)
})

function getTitle(path) {
  switch (path) {
    case '/': {
      return '登录'
    }
    case '/login': {
      return '登录'
    }
    case '/register': {
      return '注册页'
    }
    case '/home': {
      return '首页'
    }
    default: {
      return 'bbb'
    }
  }
}
export default router
